import { mountAllEMListener } from "@/IM/listener";
import { useTabsStore } from "@/stores/modules/tabs";
import { useAppStore } from "@/stores/modules/app";
import { loginApi, optTokenApi, captchaApi, loginPhoneCodeApi, phonecodeApi, loginScanCodeApi } from "@/api/modules/login";
import { useAuthStore } from "@/stores/modules/auth";
import router from "@/routers";
import { HOME_URL, LOGIN_URL } from "../configs/config";
import { ElMessage, ElNotification } from "element-plus";
import { getMenusFromMRA, getTimeState, handleRouterHash } from "@/utils";
import { ReqLoginForm, ReqLoginPCForm, loginAuth } from "../interface/login";
import { MRAItem } from "../interface/menu";
import MRA_FILES from "@/biz/configs/mra.json";
import { useImStore } from "@/stores/modules/im";
const imStore = useImStore();
const appStore = useAppStore();
const authStore = useAuthStore();
const tabStore = useTabsStore();

//* 获取操作码
export const bizOptToken = async () => {
  return await optTokenApi();
};

//* 获取验证码图片
export const bizCaptcha = async (optCode: string) => {
  return await captchaApi(optCode);
};

//* 获取短信验证码
export const bizPhoneCode = async (phone: string) => {
  return await phonecodeApi(phone);
};

//* 获取扫码登录二维码
export const bizScanCode = async () => {
  return await scancodeApi();
};

const routerAuthParser = (auths: Array<loginAuth>) => {
  let _L = [] as Array<string>;
  auths.forEach(auth => {
    _L.push(auth.module);
    if (auth.items.length > 0) {
      _L = _L.concat(routerAuthParser(auth.items));
    }
  });
  return _L;
};

// * 用户登录
export const bizLogin = async (params: ReqLoginForm) => {
  const res = await loginApi(params);
  //console.log("登录接口的返回值：", res);
  if (res && res.data) {
    //写入token， 写入用户信息
    appStore.setToken(res.data!.token);
    appStore.setUserName(res.data!.userName);
    appStore.setUserPhone(res.data!.userPhone);
    appStore.setUserAvatar(res.data!.userAvator);
    appStore.setFlagIdentity(res.data!.flagIdentity);
    appStore.setFlagCompany(res.data!.flagCompanyUser);
    appStore.setUserId(res.data!.userId);
    appStore.setImToken(res.data!.imtoken);
    let info = await imStore.doLogin();
    if (info) {
      imStore.getFetchUserInfoById(res.data!.userId)
      mountAllEMListener();
    }
    //去调用环信注册当前用户
    // let imTokenRes = await registerImApi();
    // if (imTokenRes && imTokenRes.data) {
    //   appStore.setImToken(imTokenRes.data);
    // }

    const data = getMenusFromMRA(MRA_FILES as Array<MRAItem>);
    data && authStore.setAuthMRACodes(handleRouterHash(data));
    //写入菜单权限
    authStore.setAuthRouterCodes(routerAuthParser(res.data!.auth));
    //写入按钮权限
    //清除Tags区域
    tabStore.closeMultipleTab();
    //跳转到首页
    router.push(HOME_URL);
    //提示成功登录的消息
    ElNotification({
      title: getTimeState(),
      message: "欢迎登录.",
      type: "success",
      duration: 3000
    });
  } else {
    ElNotification({
      title: getTimeState(),
      message: res.msg,
      type: "error",
      duration: 3000
    });
  }
};

// * 用户登录手机号+验证码
export const bizLoginPC = async (params: ReqLoginPCForm) => {
  const res = await loginPhoneCodeApi(params);
  if (res && res.data) {
    //写入token， 写入用户信息
    appStore.setToken(res.data!.token);
    appStore.setUserName(res.data!.userName);
    appStore.setUserAvatar(res.data!.userAvator);
    appStore.setFlagIdentity(res.data!.flagIdentity);
    //去调用环信注册当前用户
    // let imTokenRes = await registerImApi();
    // if (imTokenRes && imTokenRes.data) {
    //   appStore.setImToken(imTokenRes.data);
    // }
    const data = getMenusFromMRA(MRA_FILES as Array<MRAItem>);
    data && authStore.setAuthMRACodes(handleRouterHash(data));
    //写入菜单权限
    authStore.setAuthRouterCodes(routerAuthParser(res.data!.auth));
    //写入按钮权限
    //清除Tags区域
    tabStore.closeMultipleTab();
    //跳转到首页
    router.push(HOME_URL);
    //提示成功登录的消息
    ElNotification({
      title: getTimeState(),
      message: "欢迎登录.",
      type: "success",
      duration: 3000
    });
  } else {
    ElNotification({
      title: getTimeState(),
      message: res.msg,
      type: "error",
      duration: 3000
    });
  }
};

// * 用户登录手机号+验证码
export const bizLoginSC = async (params: ReqLoginPCForm) => {
  const res = await loginScanCodeApi(params);
  if (res && res.data) {
    //写入token， 写入用户信息
    appStore.setToken(res.data!.token);
    appStore.setUserName(res.data!.userName);
    appStore.setUserAvatar(res.data!.userAvator);
    appStore.setFlagIdentity(res.data!.flagIdentity);

    //跳转到首页
    router.push(HOME_URL);
    //提示成功登录的消息
    ElNotification({
      title: getTimeState(),
      message: "欢迎登录.",
      type: "success",
      duration: 3000
    });
    //去调用环信注册当前用户
    // let imTokenRes = await registerImApi();
    // if (imTokenRes && imTokenRes.data) {
    //   appStore.setImToken(imTokenRes.data);
    // }
    const data = getMenusFromMRA(MRA_FILES as Array<MRAItem>);
    data && authStore.setAuthMRACodes(handleRouterHash(data));
    //写入菜单权限
    authStore.setAuthRouterCodes(routerAuthParser(res.data!.auth));
    //写入按钮权限
    //清除Tags区域
    tabStore.closeMultipleTab();
    return true;
  }
  return false;
};

// * 用户登出
export const bizLogout = async () => {
  //todo 调用logoutApi接口。在服务器端清除token
  appStore.setToken("");
  router.push(LOGIN_URL);
  window.location.reload()
  ElMessage({
    type: "success",
    message: "退出登录成功！"
  });
};

// * 保存数据（新增， 修改）接口
// export const bizSave = (params: UserEntity) => {};

// * 通过 Id主键获取单个数据详情接口, 返回的对象可以直接通过 Save 接口保存
// export const bizInfo = async (id: string): UserEntity => {
//   const res = await loginApi(params);
//   return res;
// };
